package com.hyj.boxueguxiangmu.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import com.hyj.boxueguxiangmu.R;
import com.hyj.boxueguxiangmu.activity.CourseDetaleActivity;
import com.hyj.boxueguxiangmu.model.CourseModel;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/4/2.
 */

public class CourseFragment extends Fragment {
    RecyclerView mRecycleView;
    ViewPager mViewPager;
    LinearLayout mDotLayout;
    int curentpostion = 0;
    public ArrayList<CourseModel.Course> courselists = new ArrayList<>();
    public ArrayList<ImageView> mViewPagerImgs = new ArrayList<>();
    public ArrayList<ImageView> mDotImg = new ArrayList<>();
    Handler handler  = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            Log.i("CourseFragment","handleMessage" + message.what);
            handler.sendEmptyMessageDelayed(1,1000);
            curentpostion ++;
            mViewPager.setCurrentItem(curentpostion % mViewPagerImgs.size());
            return false;
        }
    });

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_course,container,false);
        mRecycleView = view.findViewById(R.id.recycleview);
        mViewPager = view.findViewById(R.id.viewpager);
        mDotLayout = view.findViewById(R.id.dotlayout);
        loading();
        return view;
    }

    public void loading(){ //主线程

        //网络请求 必须子线程请求get(_){  new Thread }


        RequestParams params = new RequestParams("http://1633.applinzi.com/public/?s=App.Course.Getcourse");//请求的域名
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {     //回调方法里面 自动切到主线程


                Gson gson  =new Gson();
                CourseModel courseModel = gson.fromJson(result,CourseModel.class);
                if (courseModel!= null&&courseModel.data!= null && courseModel.data.courselist!=null) {
                    courselists = courseModel.data.courselist;//todo 判空
                }
                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2);
                mRecycleView.setLayoutManager(gridLayoutManager);

                mRecycleView.setAdapter(new MyAdatper());


                //准备数据
                ArrayList<String> banner = courseModel.data.banner;

           ImageView imageView1 = new ImageView(getActivity());
                x.image().bind(imageView1,banner.get(banner.size()-1));
                mViewPagerImgs.add(imageView1);

                for(int i = 0 ; i < banner.size(); i++){
                    ImageView imageView = new ImageView(getActivity());
                    x.image().bind(imageView,banner.get(i));
                    mViewPagerImgs.add(imageView);
                }
               ImageView imageView2 = new ImageView(getActivity());
                x.image().bind(imageView2,banner.get(0));
                mViewPagerImgs.add(imageView2);


                mViewPager.setAdapter(new MyViewPagerAdatper());

              mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        curentpostion = position;
                        if (curentpostion == 0){
                            setIndicator(mViewPagerImgs.size()-2-1);
                        }else if (curentpostion == mViewPagerImgs.size()-1){
                            setIndicator(0);
                        }
                        setIndicator(curentpostion-1);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                        if (state !=ViewPager.SCROLL_STATE_IDLE){
                            return;
                        }
                        if (curentpostion == 0){
                            mViewPager.setCurrentItem(mViewPagerImgs.size()-2,false);
                        }else if (curentpostion ==mViewPagerImgs.size()-1 ){
                            mViewPager.setCurrentItem(1,false);
                        }

                    }
                });
                mViewPager.setCurrentItem(1);
//启一个定时器，每秒 钟 curentpostion+1；
//                handler.sendEmptyMessage(1);
                Log.i("CourseFragment","sendEmptyMessageDelayed" );
//                handler.sendEmptyMessageDelayed(1,2000);
                Log.i("LoginActivity","result:" +result);
                for (int i = 0 ; i < mViewPagerImgs.size()-2; i ++){
                    ImageView imageView = new ImageView(getActivity());
                    if (i ==0){
                        imageView.setBackgroundResource(R.drawable.ic_indicator_on);
                    }else {

                        imageView.setBackgroundResource(R.drawable.ic_indicator_off);
                    }
                    mDotImg.add(imageView);
                    mDotLayout.addView(imageView);
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void setIndicator(int position){
        for (int i = 0 ; i < mDotImg.size(); i ++){
            if (i == position){
                mDotImg.get(i).setBackgroundResource(R.drawable.ic_indicator_on);
            }else {
                mDotImg.get(i).setBackgroundResource(R.drawable.ic_indicator_off);

            }
        }
    }
    public class MyViewPagerAdatper extends PagerAdapter{

        @Override
        public int getCount() {
            return mViewPagerImgs.size();
        }

           @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = mViewPagerImgs.get(position);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewPagerImgs.get(position));

        }
    }

    //定义adpter
    public class  MyAdatper extends RecyclerView.Adapter<MyViewHolder>{

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(getActivity(),R.layout.item_course,null);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            final CourseModel.Course course = courselists.get(position);
            holder.titleTv.setText(course.title);
            holder.contentTitleTv.setText(course.titlecontent);
            x.image().bind(holder.imageView,course.icon);//图片请求
            holder.mRootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), CourseDetaleActivity.class);

                    intent.putExtra("imaurl",course.imgurl);
                    intent.putExtra("des",course.des);
                    intent.putExtra("video",course.videourl);

                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return courselists.size();
        }
    }


    public class MyViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView titleTv;
        TextView contentTitleTv;
        LinearLayout mRootView;
        public MyViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.img);
            titleTv = itemView.findViewById(R.id.title);
            contentTitleTv = itemView.findViewById(R.id.contenttitle);
            mRootView = itemView.findViewById(R.id.rootview);
        }
    }

}
